<template>
    <a-layout id="components-layout-demo-fixed-sider" style="height: 100%">
        <!--左边应用-->
        <div class="shade" @click="useShow=false,useId = ''" v-if="useShow"></div>
        <a-layout>
            <a-layout-header class="hearlist" :style="{background:background}">
                <div class="container-layout">
                   <div> <main-head @handClick="handClick" :appKey="appKey" :menus="menus" :background="background"></main-head></div>
                    <div>
                        <right-tool-bar></right-tool-bar>
                    </div>
                </div>
                <div></div>
            </a-layout-header>
            <a-layout-content class="innerLayoutCenter">
                <!--面包屑-->
                <navigation-bar :collapsed="collapsed" @navClick="navClick" @setFrontmenu="setFrontmenu" @adhibitionUser="adhibitionUser"></navigation-bar>
                <div class="innerBox">
                    <keep-alive>
                        <router-view  />
                    </keep-alive>
                </div>
            </a-layout-content>
        </a-layout>

    </a-layout>
</template>

<script>
import router from '@/router';
import RightToolBar from './compoment/main/RightToolBar';
import {mapActions, mapGetters, mapMutations, mapState} from "vuex";

import {getParentNode} from "@/utils/routerUtil";
import SysPublicApi from "@/api/system/core/public"
import MainUse from "./compoment/main/MainUse";
import MainHead from "../layouts/MainHead";
import NavigationBar from "./compoment/main/NavigationBar";
import {ParamsEncrypt,Util,TokenUtil} from "@lowcode/jpaas-common-lib";
import SysAppApi from "@/api/system/core/sysApp";
import SysSiteSettingApi from "@/api/system/core/sysSiteSetting";

export default {
    name: 'inner-layout',
    components: {
        RightToolBar,
        MainUse,
        MainHead,
        NavigationBar,
    },
    mixins:[ParamsEncrypt],
    computed: {
        ...mapState({
            menus: state => state.appSetting.menus,
            appKey: state => state.appSetting.appKey,
            menuMap: state => state.appSetting.menuMap,
            navigation: state => state.appSetting.navigation,
            loading: state => state.appSetting.loading,
            switching: state => state.appSetting.switching,
            background: (state) => state.appSetting.background,
            showType: state => state.appSetting.showType,
            activeKey: state => state.appSetting.activeKey,
            systemStyle: (state) => state.appSetting.systemStyle,
        }),
        ...mapGetters({
            fullName: 'fullName'
        }),
    },
    data() {
        return {
            routeKeepAlive: true,
            routeKey: 'K',
            leftMenu: {},
            arr: [],
            width:'246px',
            isFold:false,
            current: ['mail'],
            collapsed: false,
            menuPathlist: [],
            appName: '企业平台',
            customArr: ['customIcon', 'userCustomIcon','jpaasIcon'],
            useId: '',//应用标识，use常规，collect收藏应用
            useShow: false,//是否展示应用
            //默认logo
            homePageLogoUrl: process.env.BASE_URL + 'image/log.png',
            //默认透明logo
            homePageLucentLogoUrl: process.env.BASE_URL + 'image/logo_white.png',
        }
    },
    created() {
        let self = this;
        this.getAllApps();
        this.getConfig();
        //默认第一条数据
        this.getMenu();
       // this.setCmptArr();
        this.$bus.on('handUrlClick', (item) => {
            self.leftMenu = item;
            self.setAppKey(item.key); //添加面包屑
        })
        SysPublicApi.getSysAppConfigs().then(resp => {
            if (resp.appName) {
                self.appName = resp.appName;
            }
        });
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "layoutsLang", key);
        },
        ...mapActions({Logout: "user/Logout"}),
        ...mapMutations('appSetting', ['setAppKey', 'setMenuPath', 'setSelecteKeys', 'setActiveKey', 'setBreadList','setOpenKeys','setAllApps']),
        getAllApps(){
            //获取所有应用
            SysAppApi.getAllApps().then(res=>{
                var apps={};
                res.map(app=>{
                    apps[app.appId]={appName:app.clientName,}
                });
                this.setAllApps(apps);
            });
        },
        mainUseclick(item) {
            this.useId = item;
            this.useShow = true
        },
        handClick(item) {
            //用户开发应用
            if (item.appType == '1' && item.menuNavType == '1') {
                var path = item.appPath ? item.appPath : "/apps";
                window.open(path + "/" + item.key, '_blank');
                return;
            }
            //外部链接情况
            if (item.layout && item.layout == "external") {
                window.open(item.params, '_blank');
                return;
            }
            this.setAppKey(item.key);
            //在应用开发中让路由定位在Mainlayout组件中
            this.$router.push({path:'/'});
            this.firstActive(item);
        },
        adhibitionUser(item) {
            this.close();
            this.setAppKey(item.key); //添加面包屑
            this.firstActive(item);
        },
        close() {
            this.useShow = false;
            this.useId = '';
        },
        getChilren(item) {
            let _item = item;
            if (_item.showType && _item.component) {
                return _item;
            }
            while (_item.children) {
                this.switching == "crumbs" ? this.columnlist(_item) : '';
                _item = _item.children[0];
            }
            return _item;
        },
        //面包屑
        handNavBars(item) {
            let tabs=this.navigation[this.frontType];

            for (var nav of tabs) {
                if (nav.key == item.key) {
                    this.setActiveKey(item.key)
                    return;
                }
            }
            this.setActiveKey(item.key);
            tabs.push(item);
        },
        firstActive(item) {//点击头部导航 默认打开左边第一个菜单；
            let _item = this.getChilren(item);
            //添加-导航栏；
            this.handNavBars(_item);
            if (_item.showType == 'URL') {
                //URL访问
                this.openUrl(_item);
            } else if (_item.showType == 'NEW_WIN') {
                //新窗口
                this.openNewWin(_item);
            }
            //第一个菜单为弹窗时不默认打开
            else if (_item.showType == 'POP_WIN') {
                this.$message.warning( this.i18n('innerLayout.complete','第一个菜单为弹窗时不默认打开!'));
            }

        },
        columnlist(item) {
            let parentArr = getParentNode(this.menus, item.id).reverse();
            this.setBreadList(parentArr);
        },
        openUrl(item) {
            var name = item.key;
            var pathParams = {name: name};
            this.setSelecteKeys([item.key]);
            if (item.params) {
                pathParams.params = {params: item.params};
            }
            this.generatePath(item.id);
            if (this.showType == 'window') {
                router.push(pathParams);
            }
        },
        navClick(pane) { //导航 对应展开左侧菜单 yx;
            let _menus = this.menus;
            if (pane.id) {
                let parentMenuArr = getParentNode(_menus, pane.id);
                this.leftMenu = parentMenuArr[parentMenuArr.length - 1];
                this.setAppKey(parentMenuArr[parentMenuArr.length - 1].key);
                if (parentMenuArr[1]) {
                    this.setOpenKeys([parentMenuArr[1].key]);
                }
            }else
            if(pane.key == "home-index"){
                this.leftMenu = {};
            }
        },
        openNewWin(item) {
            var path = process.env.VUE_APP_ADMIN_FRONT;
            var aryMenuPath = this.getMenuPath(item.id);
            var url = path;
            for (var i = 0; i < aryMenuPath.length; i++) {
                url += "/" + aryMenuPath[i].menuKey;
            }
            window.open(url, '_blank');
        },
        generatePath(id) {
            var aryMenuPath = this.getMenuPath(id);
            //将菜单路径发布到VUEX
            this.setMenuPath(aryMenuPath)
        },
        getMenuPath(id) {
            var aryMenuPath = [];
            var obj = this.menuMap[id];
            aryMenuPath.push(obj)

            while (obj.parentId != '0') {
                obj = this.menuMap[obj.parentId];
                aryMenuPath.unshift(obj);
            }
            return aryMenuPath;
        },
        goToPath(name) {
            router.push({name: name});
        },
        getMenu() {
            if (!this.appKey[0]) {
                this.collapsed = true;
                this.isFold = true;
            }
            if(this.menus.length !=0){
                for (var i = 0; i < this.menus.length; i++) {
                    var menu = this.menus[i];
                    if (menu.key == this.appKey[0]) {
                        this.leftMenu = menu;
                        this.$set(this.leftMenu, 'key', menu.key)
                    }
                }
            }else {
                this.collapsed = true;
                this.isFold = true;
            }
        },
        toggle() {
            this.collapsed = !this.collapsed;
            this.isFold = !this.isFold;
        },
        setFrontmenu(item){
            this.leftMenu = item;
        },
        getConfig() {
          let self_=this;
          SysSiteSettingApi.getConfig().then((res) => {
            if (res.success) {
              if (res.data && res.data.confs) {
                let confs = JSON.parse(res.data.confs);
                if(confs.homePageLogo) {
                  self_.homePageLogoUrl = self_.getFilePath(confs.homePageLogo);
                }
                if(confs.homePageLucentLogo) {
                  self_.homePageLucentLogoUrl = self_.getFilePath(confs.homePageLucentLogo);
                }
              }
            }
          })
        },
        getFilePath(fileId){
          let token = TokenUtil.getToken();
          fileId=Util.encryptWord(fileId);
          return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
    },
    watch: {
        $route(to, from) { //監聽路由變化 刷新組件;
            let _urlType = "";
            if (this.$route.params && this.$route.params.urlType) {
                _urlType = this.$route.params.urlType;
            }
            if (this.$route.fullPath.indexOf('editPage') > -1 || _urlType) {
                this.routeKeepAlive = false;
                this.routeKey = "K" + new Date().getTime();
            } else {
                this.routeKeepAlive = true
            }
        },
        navigation: {
            handler: function(o, ol) {
                //this.setCmptArr();
            },
            deep: true
        },
        activeKey(o, ol) {
            if (this.showType != 'window') {
                this.$nextTick(function() {
                    let pre = this.$refs['ref' + o];
                    if (pre && pre[0].newPageInit) {
                        pre[0].newPageInit(o);
                    }
                })
            }
        },
        leftMenu:{
            //当菜单为空时候关闭展示
            handler:function (o,ol){
                if(o.children){
                    this.width = '246px';
                    this.collapsed = false;
                    this.isFold = false;
                }else {
                    this.width ='66px';
                }
            },
            deep:true
        }
    }
}
</script>

<style scoped="scoped">
.shade {
    position: absolute;
    top: 0px;
    left: 65px;
    width: calc(100% - 65px);
    height: 100%;
    z-index: 999;
    background: rgba(0, 0, 0, .2);

}

.amenu_head {
    display: flex;
    flex-direction: column;
}

.amenu_head span:nth-child(1) {
    height: 25px;
    line-height: 35px;
    text-align: center;
    margin-top: 10px;
}

.menuBox_white >>> .amenu_head span:nth-child(1) i,
.menuBox_white >>> .amenu_head span:nth-child(2) {
    color: #555;
}

.amenu_head span:nth-child(2) {
    line-height: 40px;
    height: 40px;
    color: white;
    text-align: center;
}

.amenu_head span:nth-child(1) i {
    font-size: 22px;
    color: white;
    margin-left: 10px;
}

.layout-logo img {
    width: 45px;
    height: 45px;
    margin: 16px 7.5px 0px 7.5px;
}

.layout-logo {
    height: 79px;
}

/*应用样式*/
.rxMainLayoutUse_iconfont {
    position: relative;
}

.rxMainLayout_mainuse {
    position: absolute;
    top: 0px;
    left: 66px;
    width: calc(100vw - 80px) !important;
    min-height: 600px !important;
    max-height: 80vh;
    overflow: hidden;
    background-color: white;
    box-shadow: 0px 0px 10px 0px rgba(0, 21, 41, 0.16);
    border: solid 1px #dfdfdf;
    z-index: 999;
}

.rxMainLayoutUsetriangle {
    display: block;
    position: absolute;
    top: 27px;
    left: 53px;
    height: 6px;
    width: 10px;
    border: 7px solid;
    z-index: 9999;
    border-color: transparent white transparent transparent;
}

.rxMainLayoutcollect {
    display: block;
    position: absolute;
    top: 90px;
    left: 53px;
    height: 6px;
    width: 10px;
    border: 7px solid;
    z-index: 9999;
    border-color: transparent white transparent transparent;
}

.rxMainLayoutUse_iconfont > div {
    width: 46px;
    text-align: center;
    overflow: hidden;
    line-height: 46px;
    margin: auto;

}

.rxMainLayoutUse_iconfont > div > span {
    width: 46px;
    height: 46px;
    line-height: 46px;
    border-radius: 5px;
    display: block;
    margin: 10px 0px;
}

.rxMainLayoutUse_iconfont > div:hover > span, .rxMainLayoutUse_iconfont_hover {
    background-color: #464c67;
    cursor: pointer;
}

.rxMainLayoutUse_iconfont_hover i {
    color: white !important;
}

.rxMainLayoutUse_iconfont > div:nth-child(1) {
    border-bottom: 1px solid #464c67;
}

.rxMainLayoutUse_iconfont > div i {
    font-size: 22px;
}

.rxMainLayoutUse {
    display: flex;
    flex: 1;
    width: 266px;
    height: 100%;
    border-top: 1px solid rgba(0, 0, 0, .1);
}

.rxMainLayoutUse > div:nth-child(1) {
    width: 66px;
    border-right: 1px solid #464c67;
}

.rxMainLayoutUse > div:nth-child(2) {
    width: 180px;
}

.rxMenuBox {
    background-color: #29304c;
}

.container-layout {
    display: flex;
    flex: 1;
    flex-direction: row;
}
.container-layout > div:nth-child(1){
    flex: 1;
}
.cenlist {
    min-width: 540px;
    line-height: normal;
    position: relative;
}

.menuBox .ant-menu-horizontal {
    border-bottom: 0;
}

.hearlist {
    line-height: normal;
    padding: 0;
    height: 50px !important;
}

.loglin {
    white-space: nowrap;
    padding: 14px 20px 0;
    color: #fff;
    font-size: 20px;
}

.loglin img {
    width: 30px;
    vertical-align: middle;
}

.loglin span {
    vertical-align: middle;
    padding-left: 10px;
}

.menuBox >>> .ant-menu-item a,
.menuBox >>> .ant-menu-submenu {
    color: #fff;
}

.innerLayoutCenter {
    flex: 1;
    position: relative;
}

.innerLayoutCenter .innerBox {
    position: absolute;
    top: 38px;
    bottom: 0;
    width: 100%;
    box-sizing: border-box;
    overflow: auto;
}
</style>